package com.shierke.Ume.util

import android.content.Context
import java.util.*
import android.os.Build
import com.google.gson.Gson


/**
 * Create by Ybx
 * on 2020-10-11
 * Desribe:
 */
class LanguageUtil {


    companion object {


        const val LOCALE_SP: String = "LOCALE_SP"
        const val LOCALE_SP_KEY: String = "LOCALE_SP_KEY"

        fun getLocale(context: Context): Locale {
            val spLocale = context.getSharedPreferences(LOCALE_SP, Context.MODE_PRIVATE)
            val localeJson = spLocale.getString(LOCALE_SP_KEY, "")
            val gson = Gson()
            return gson.fromJson(localeJson, Locale::class.java)
        }

        private fun setLocale(pContext: Context, pUserLocale: Locale) {
            val spLocal = pContext.getSharedPreferences(LOCALE_SP, Context.MODE_PRIVATE)
            val edit = spLocal.edit()
            val json = Gson().toJson(pUserLocale)
            edit.putString(LOCALE_SP_KEY, json)
            edit.apply()
        }


        fun updateLocale(context: Context, locale: Locale): Boolean {
            if (needUpdateLocale(context, locale)) {
                val configuration = context.resources.configuration
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
                    configuration.setLocale(locale)
                } else {
                    configuration.locale = locale
                }
                val displayMetrics = context.resources.displayMetrics
                context.resources.updateConfiguration(configuration, displayMetrics)
                setLocale(context, locale)
                return true
            }
            return false
        }


        fun needUpdateLocale(pContext: Context, newUserLocale: Locale?): Boolean {
            return newUserLocale != null && !getCurrentLocale(pContext).equals(newUserLocale)
        }

        fun getCurrentLocale(context: Context): Locale {
            val locale: Locale
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { //7.0有多语言设置获取顶部的语言
                locale = context.resources.configuration.locales.get(0)
            } else {
                locale = context.resources.configuration.locale
            }
            return locale
        }
    }
}